<template>
  <div class="app-container">
    {{carInfoId}}-1-{{imageList}}
<!--<el-input :value="data_is_null" @change="data_is_null"/>-->

    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="图片" prop="carName">
        <div class="demo-image">
          <el-avatar v-for="img in imageList" shape="square" :size="100" fit="true" :src="img.fileUrl"></el-avatar>
        </div>
<!--        <input id="filePath" name="filePath" multiple class="form-control" type="file" @change="subUpload">-->
        <div id="app">
          <div class="upload">
            <input type="file" id="file" multiple @change="upload">
          </div>
          <ul class="view">
<!--            <li>-->
              <!--          <img src="./img/52.jpg">-->
<!--              <div class="delect" title="删不了我" @click="noDelect">×</div>-->
<!--            </li>-->
            <li v-for="(item,index) in list" :key="index" >
              <img :src="item">
              <div class="delect" @click="delect(index)">×</div>
            </li>
          </ul>
        </div>
      </el-form-item>
      <el-form-item label="车款名称" prop="carName">
        <el-input v-model="form.carName" placeholder="请输入车款名称" />
      </el-form-item>
      <el-form-item label="介绍">
        <editor v-model="form.content" :min-height="192"/>
      </el-form-item>
<!--      <el-form-item label="删除标志" prop="delFlag">-->
<!--        <el-input v-model="form.delFlag" placeholder="请输入删除标志" />-->
<!--      </el-form-item>-->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>
<script>
import { getInfo, delInfo, addInfo, updateInfo } from "@/api/car/info";
import {listFile, listUploadFile} from "@/api/car/car_file";
import {getToken} from "@/utils/auth";
export default {
  name: "CarInfo",
  props: ['carInfoId','busType'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆车款表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandId: null,
        seriesId: null,
        modelId: null,
        carName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        brandId: [
          { required: true, message: "品牌ID不能为空", trigger: "change" }
        ],
        seriesId: [
          { required: true, message: "车系ID不能为空", trigger: "change" }
        ],
        modelId: [
          { required: true, message: "车型ID不能为空", trigger: "change" }
        ]
      },
      imageList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      list:[]
    };
  },
  created() {
    console.log('created')
    this.getInitData();
  },
  activated() {
    console.log('activated')
    this.getInitData();
  },
  destroyed() {
    console.log('destroyed')
  },
  methods: {
    getInitData(){
      this.getList()
      this.getFileList();
    },
    /** 查询车辆车款列表 */
    getList() {
      console.log('父组件传递参数：',this.carInfoId)
      this.loading = true;
      getInfo(this.carInfoId).then(response => {
        this.form = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        carId: null,
        brandId: null,
        seriesId: null,
        modelId: null,
        carName: null,
        content: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.carId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车辆车款";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const carId = row.carId || this.ids
      getInfo(carId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车辆车款";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.carId != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const carIds = row.carId || this.ids;
      this.$modal.confirm('是否确认删除车辆车款编号为"' + carIds + '"的数据项？').then(function() {
        return delInfo(carIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('car/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    getFileList(){
      this.loading = false;
      listFile({busType:this.busType,busId:this.carInfoId}).then(response => {
        console.log(response)
        this.imageList = response.rows;
        console.log(this.imageList)
        this.loading = false;
      });
    },upload:function(e) {
      //e.target指向事件执行时鼠标所点击区域的那个元素，那么为input的标签，
      // 可以输出 e.target.files 看看，这个files对象保存着选中的所有的图片的信息。
      console.log(e.target.files)
      //------------------------------------------------------
      // 既然如此，循环这个files对象，用for of 循环，
      for(let item of e.target.files){
        //正则表达式，判断每个元素的type属性是否为图片形式，如图
        if (!/image\/\w+/.test(item.type)) {
          // 提示只能是图片，return
          alert("只能选择图片");
          return;
        }
        // 保存下当前 this ，就是vue实例
        var _this = this;
        //  创建一个FileReader()对象，它里面有个readAsDataURL方法
        let reader = new FileReader();
        // readAsDataURL方法可以将上传的图片格式转为base64,然后在存入到图片路径,
        //这样就可以上传电脑任意位置的图片
        reader.readAsDataURL(item);
        //文件读取成功完成时触发
        reader.addEventListener('load',function(){
          //  reader.result返回文件的内容。
          //只有在读取操作完成后，此属性才有效，返回的数据的格式取决于是使用哪种读取方法来执行读取操作的。
          //给数组添加这个文件也就是图片的内容
          _this.list.push(this.result);
          // console.log(_this.list[0]);
        listUploadFile({'busType':_this.busType,busId:_this.carInfoId,'base64Img':this.result,aaa:1});
        });
      }
      //------------------------------------------------------------
    },
    delect:function (index){
      console.log(index);
      this.list.splice(index,1);
    },
    // 这是默认图片的方法，弹出默认图片无法删除
    noDelect:function (){
      alert('默认图片无法删除。')
    },
    subUpload:function (){
      var formData = new FormData();
      if ($('#filePath')[0].files[0] == null) {
        $.modal.alertWarning("请先选择文件路径");
        return false;
      }
      formData.append('fileName', $("#fileName").val());
      formData.append('file', $('#filePath')[0].files[0]);
      $.ajax({
        url:  "/file/add",
        type: 'post',
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(result) {
          $.operate.successCallback(result);
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
#app{
  width: 900px;
  background-color: rgb(241, 241, 241);
  margin: 50px auto;
}
.view{
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  align-items: space-around;
}.view > li{
   width: 200px;
   height: 120px;
   background-color: rgba(54, 194, 35,0.1);
   list-style: none;
   margin: 20px;
   position: relative;
 }
.view > li > img{
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.delect{
  position: absolute;
  right: 0;
  top: 0;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  font-size: 15px;
  background-color: rgba(255, 255, 255,0.5);
  user-select: none;
  cursor: pointer;
  opacity: 0;
}
.delect:hover{

  background-color: rgba(31, 31, 31, 0.5);
  color: white;
}
.view>li:hover .delect{
  opacity: 1;
} .upload{
    width: 80px;
    height: 20px;
    background-color: rgba(135, 206, 235,0.2);
    border: 1px dashed black;
    border-radius: 5px;
    position: relative;

  }
.upload:hover{
  background-color: rgba(135, 206, 235,1);
}
.upload::before{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  content: '上传图片';
  font-size: 13px;
  text-align: center;
  font-family: 'fangsong';
  line-height: 20px;
  user-select: none;
}
#file{
  width: 100%;
  height: 100%;
  opacity: 0;
}
</style>
